<script setup>
import {ref,computed,onMounted} from 'vue'
import {ElMessageBox} from "element-plus";
import router from "@/router/index.js";
import {useRoute} from "vue-router";
import {getDetailOrderListAPI, updateOrderAPI} from "@/apis/order.js";
import {useUserStore} from "@/stores/user.js";
import {alipay} from "@/apis/alipay.js";


// 选择的倒计时初始值
const selectedHours = ref(0);
const selectedMinutes = ref(10);
const selectedSeconds = ref(0);

// 当前剩余的倒计时时间，以秒为单位动态更新
const totalSeconds = ref(0);

// 表示倒计时是否正在运行，用来防止重复启动计时器
const isRunning = ref(false);

// 存储定时器的句柄，用于管理 setInterval
let timer = null;

// computed：这是一个计算属性，动态计算剩余时间的格式化显示。
const formattedTime = computed(() => {
  const hours = Math.floor(totalSeconds.value / 3600);
  const minutes = Math.floor((totalSeconds.value % 3600) / 60);
  const seconds = totalSeconds.value % 60;
  // 返回格式用于倒计时器的显示 hh:mm:ss
  //return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  return `${String(minutes)}:${String(seconds).padStart(2, '0')}`;
});


// 将计算结果赋值给 totalSeconds，作为倒计时的起始值。
const initializeCountdown = () => {
  totalSeconds.value = selectedHours.value * 3600 + selectedMinutes.value * 60 + selectedSeconds.value;
};


const startCountdown = () => {
  if (totalSeconds.value === 0) {
    initializeCountdown(); // 如果总秒数为0，重新初始化
  }
  // 通过 isRunning 确保倒计时只能启动一次
  if (!isRunning.value) {
    isRunning.value = true;
    // 使用 setInterval 每秒执行一次回调
    timer = setInterval(() => {
      if (totalSeconds.value > 0) {
        totalSeconds.value -= 1; // 每秒减1
      } else {
        // 调用 pauseCountdown 停止计时器
        pauseCountdown();
      }
    }, 1000);
  }
};

const pauseCountdown = () => {
  // 将 isRunning 设置为 false，标记倒计时暂停
  isRunning.value = false;
  // 如果计时器已存在（timer 不为 null），调用 clearInterval 停止计时器，并将 timer 置空
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

onMounted(()=>{
  //开始支付倒计时，10分钟
  startCountdown()
  orders.value=JSON.parse(useRoute().query.data)
})
const orders=ref([])
const doPay=async ()=> {
  let flag=true
  for (const item of orders.value) {
    const res= await updateOrderAPI(item, 2)
      if (res.code !== 200) {
        //订单支付失败
        flag= false
        console.log("支付失败")
      }
    }
  if (flag) {
    successDialogVisible.value = true
    //启动回首页倒计时
    goBack()
  } else {
    failDialogVisible.value = true
  }
}

const payRadio = ref('Alipay')
const loading = ref(false)
const successDialogVisible=ref(false)
const failDialogVisible=ref(false)


async function payByAlipay() {
  //获取订单详情
  const orderList=await getDetailOrderListAPI(useUserStore().userInfo.uid)
  //过滤
  orderList.data=orderList.data.filter(order=>orders.value.includes(order.oid))

  if (!orderList.data || orderList.data.length === 0) {
    ElMessageBox.alert('无法找到要支付的订单详情，请返回重试。', '支付错误', {
      confirmButtonText: '确定',
    });
    return; // 终止执行
  }

  //console.log("详细订单列表",orderList.data)
  //支付
  const orderData={
    oid:orderList.data[0].oid,
    title:orderList.data[0].goods[0].title,
    goods_detail:[],
    total_amount:orderList.data[0].total_price
  }
  orderList.data[0].goods.forEach(goods=>{
    const item={
      goods_id:goods.gid,
      goods_name:goods.title,
      quantity:goods.amount,
      price:goods.unit_price,
      body:goods.tagsStr
    }
    orderData.goods_detail.push(item)
  })
  //转到支付宝页面
  await alipay(orderData).then(url=>{
    window.open(url, '_self')
  })
}

function handlePay() {
  if(payRadio.value==='Alipay'){
    payByAlipay()
  }else{
    //显示加载层
    loading.value=true
    //倒计时1s
    let TIME_COUNT = 1;
    timer=setInterval(() => {
      if (TIME_COUNT >=1 ) {
        //限制倒计时区间
        TIME_COUNT--;
        console.log(TIME_COUNT)
      } else {
        //清除定时器
        clearInterval(timer)
        //1秒后关闭加载层
        loading.value=false
        //pay
        doPay()
      }
    }, 400)
  }
}

const goBack_time=ref(0)
function goBack() {
  //倒计时2s
  goBack_time.value= 2;
  timer=setInterval(() => {
    if (goBack_time.value >=1 ) {
      //限制倒计时区间
      goBack_time.value--;
    } else {
      //清除定时器
      clearInterval(timer)
      router.replace({
        path: "/homePage",
        query: {
          date:new Date().getTime()
        }
      })
    }
  }, 1000);
}

</script>

<template>
<div class="page" >
  <div class="logo">
    <img style="height: 60px;width: auto;margin-left: 40px;margin-top: 20px" src="../../assets/SAS-logo.png" alt="">
  </div>
  <div class="body" v-loading="loading" element-loading-text="正在支付...">
    <div class="title">
      <template v-if="useRoute().query.type==='direct'">
        <h2>订单创建成功，请在10分钟内支付</h2>
        <h1>{{formattedTime}}</h1>
      </template>
      <template v-else-if="useRoute().query.type==='order'">
        <h2>请尽快付款</h2>
      </template>

    </div>
    <h3>选择支付方式</h3>
    <div style="display: flex;flex-direction: row; justify-content: center;margin-top: 100px;">
      <el-radio-group v-model="payRadio" style="column-gap: 60px">
        <el-radio value="Alipay">
          <template #default>
            <img style="width: 180px;height: 180px" src="@/assets/img/alipay.png" alt="">
          </template>
        </el-radio>
        <el-radio value="WeChatPay">
          <template #default>
            <img style="width: 180px;height: 180px" src="@/assets/img/wechatPay.png" alt="">
          </template>
        </el-radio>
        <el-radio value="UnionPay">
          <template #default>
            <img style="width: 180px;height: 180px" src="@/assets/img/unionPay.png" alt="">
          </template>
        </el-radio>
      </el-radio-group>
    </div>
    <div style="margin-top: 200px">
      <span style="font-size: 18px;font-weight: bold">合计</span>
      <span style="font-size: 14px;font-weight: bold;color: #ff5000">￥</span>
      <span style="font-size: 22px;font-weight: bold;color: #ff5000">{{ useRoute().query.total }}</span>
      <el-button style="margin-left: 350px;width: 180px;height: 40px;color: white;background-color: #ff5000;
font-weight: bold;font-size: 14px;border-radius: 8px" @click="handlePay">
        确认支付</el-button>
    </div>
  </div>

  <el-dialog v-model="successDialogVisible" title="提示" width="500">
    <el-result icon="success" title="支付成功" :sub-title="goBack_time+'s后自动返回'"></el-result>
  </el-dialog>
  <el-dialog v-model="failDialogVisible" title="提示" width="500">
    <el-result icon="error" title="支付失败" sub-title="请检查网络"></el-result>
  </el-dialog>

</div>
</template>

<style scoped lang="less">
.page{
  width: 100%;
  height: auto;
  background-color: #f3f6f8;
  padding-bottom: 100px;
}
.body{
  margin-top: 20px;
  width: 1000px;
  height: 600px;
  background-color: white;
  border-radius: 10px;
  margin-left: auto;
  margin-right: auto;
  padding:20px;



}
.title{
  text-align: center;
}
.pay{
  width: 200px;
  height: 200px;
  border: #409EFF;
  border-radius: 10px;
  margin-right: 20px;
}
</style>